package cn.kuick.iplocation.md5;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
通过得到文件的MD5值判断两个文件是否相同
 */
public class MD5Utils {
    private static final Log log = LogFactory.getLog(MD5Utils.class);

    public static boolean fileIsSame(File file1, File file2){
        boolean isSame = false;

        byte[] file1Bytes = getFileByteStream(file1);
        byte[] file2Bytes = getFileByteStream(file2);

        String file1Md5 = getMD5(file1Bytes);
        String file2Md5 = getMD5(file2Bytes);

        System.out.println("file1Md5= " + file1Md5+ "  file2Md5= " +file2Md5);
        if(file1Md5.equals(file2Md5)){
            isSame = true;
        }
        return isSame;
    }

    public static byte[] getFileByteStream(File file){
        byte[] fileBytes = new byte[(int) file.length()];

        try {
            InputStream inputStream = new FileInputStream(file);
            try {
                inputStream.read(fileBytes);
            } catch (IOException e) {
                log.error("读取文件字节流失败!");
            }
        } catch (FileNotFoundException e) {
            log.error("文件流初始化失败！");
        }

        return fileBytes;
    }

    public static String getMD5(byte[] fileBytes){
        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        byte[] tempBytes = fileBytes;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(tempBytes);

            byte[] hashCodeBytes = messageDigest.digest();
            int j = hashCodeBytes.length;
            System.out.println("散列码长度:" + j);

            char[] str = new char[j * 2];
            int k = 0;
            for(int i = 0; i<j; i++){
                byte hashByte = hashCodeBytes[i];
                str[k++] = hexDigits[hashByte>>>4 & 0xf];
                str[k++] = hexDigits[hashByte & 0xf];
            }

            return new String(str);

        } catch (NoSuchAlgorithmException e) {
            log.error("字符信息初始化失败!");
        }

        return null;
    }
}





































